<template>
  <div>
    <van-nav-bar title="决策追踪" left-text="返回" right-text="筛选" left-arrow
                 @click-left="$router.push('/mine/stock')"
                 @click-right="showPopup1 = true"/>
    <kline-chart :data="klineArray" :showPeriods="['d', 'w', 'm']" @change="setHistory">
      <span>{{ activeData.symbol }}/{{ activeData.title }}</span>
      <span :style="{color: getColor(activeData.profit_rate)}">{{ activeData.profit_rate.toFixed(2) }}%</span>
    </kline-chart>
    <custom-table ref="tableRef" :columns="tableColumns" :records="tableData.datas"
                  :style="{ height: `${tableHeight}px` }" @onClick="onCheck" @onSort="onSort"/>
    <pager v-model="queryParams.page" :total="tableData.total" :limit="queryParams.limit"
           :count="tableData.datas.length" @change="load"/>
  </div>
</template>

<script>
import {toDateString} from '@/utils'

export default {
  components: {
    ColorText: () => import('@/components/ColorText.vue'),
    CustomTable: () => import('@/components/CustomTable.vue'),
    KlineChart: () => import('@/components/KlineChart.vue'),
    Pager: () => import('@/components/Pager.vue'),
  },
  computed: {
    tableHeight() {
      return window.innerHeight - 358
    }
  },
  data() {
    return {
      activeData: {
        market: 'sz',
        symbol: '000001',
        title: '平安银行',
        profit_rate: 0,
        open_timestamp: new Date().getTime() / 1000,
        end_timestamp: new Date().getTime() / 1000,
      },
      lastField: 'open_timestamp',
      klinePeriod: 'd',
      klineArray: [],
      queryParams: {
        page: 1,
        limit: 20,
        order_by: 'sector',
        sort_direction: 1,
        level: null,
        open_policy_hex_id: null,
        close_policy_hex_id: null,
        settled: true
      },
      tableColumns: [{
        title: '名称',
        field: 'title',
        renderCell: (row) => {
          return `<div style="color:${this.getColor(row.profit_rate)};">${row.title}</div>`
        }
      }, {
        title: '方向',
        field: 'direction',
        renderCell: (row) => {
          return `<div style="color:${row.direction === 'long' ? '#F56C6C' : '#67C23A'};">${row.direction === 'long' ? '多头' : '空头'}</div>`
        }
      }, {
        title: '代码',
        field: 'symbol',
        renderCell: (row) => {
          return `<div>${row.symbol}</div>`
        }
      }, {
        title: '等级',
        field: 'level',
        renderCell: (row) => {
          return `<div>${row.level}</div>`
        }
      }, {
        title: '开仓时间',
        field: 'open_timestamp',
        renderCell: (row) => {
          return `<div>${toDateString(new Date(row.open_timestamp * 1000))}</div>`
        }
      }, {
        title: '开仓价格',
        field: 'open_price',
        renderCell: (row) => {
          return `<div>${row.open_price}</div>`
        }
      }, {
        title: '平仓时间',
        field: 'close_timestamp',
        renderCell: (row) => {
          return `<div>${toDateString(new Date(row.close_timestamp * 1000))}</div>`
        }
      }, {
        title: '平仓价格',
        field: 'close_price',
        renderCell: (row) => {
          return `<div>${row.close_price}</div>`
        }
      }, {
        title: '浮动盈亏',
        field: 'profit_rate',
        renderCell: (row) => {
          return `<div style="color:${this.getColor(row.profit_rate)};">${row.profit_rate}%</div>`
        }
      }],
      tableData: {
        total: 0,
        datas: []
      },
      showPopup1: false
    }
  },
  methods: {
    load() {
      this.$requests.post('/china_stock/holden/obtain', this.queryParams).then(resp => {
        this.tableData = resp
        if (this.tableData.total > 0) {
          this.onCheck(this.tableData.datas[0])
        }
      })
    },
    getColor(value) {
      if (value > 0) {
        return '#F56C6C'
      } else if (value < 0) {
        return '#67C23A'
      } else {
        return '#2c3e50'
      }
    },
    setHistory(period) {
      this.klinePeriod = period
      let payload = {
        market: this.activeData.market,
        symbol: this.activeData.symbol,
        period: period.toUpperCase(),
        end: this.activeData[this.lastField]
      }
      this.$requests.post('/china_stock/klines/obtain', payload).then(res => {
        this.klineArray = res.map(item => {
          return {
            timestamp: new Date(item.datetime.replace(new RegExp('-', 'g'), '/')).getTime(),
            open: parseFloat(item.open),
            close: parseFloat(item.close),
            high: parseFloat(item.high),
            low: parseFloat(item.low),
            volume: parseFloat(item.volume),
            amount: parseFloat(item.amount)
          }
        })
      })
    },
    onCheck(item, field) {
      if (field && field.startsWith('close')) {
        this.lastField = 'close_timestamp'
      } else {
        this.lastField = 'open_timestamp'
      }
      this.activeData = item
      this.setHistory(this.klinePeriod)
    },
    onSort(order_by, sort_direction) {
      this.queryParams.order_by = order_by
      this.queryParams.sort_direction = sort_direction
      this.load()
    }
  },
  mounted() {
    this.load()
  }
}
</script>

<style scoped>

</style>
